<?php
/**
 * @since   2022-02-20
 * @author  zhaoxiang <zhaoxiang051405@gmail.com>
 */

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Middleware\AdminMiddleware;
use App\Model\AdminApp;
use App\Model\AdminGroup;
use App\Model\AdminList;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;

#[Controller(prefix: '/admin/InterfaceGroup'), Middleware(AdminMiddleware::class)]
class InterfaceGroupController extends BaseController {
    /**
     * 获取接口组列表
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[GetMapping(path: 'index')]
    public function index(): array {
        $limit = $this->request->query('size', config('apiadmin.admin_list_default'));
        $type = $this->request->query('type', '');
        $keywords = $this->request->query('keywords', '');
        $status = $this->request->query('status', '');

        $obj = AdminGroup::query();
        if (strlen($status)) {
            $obj = $obj->where('status', $status);
        }
        if ($type) {
            switch ($type) {
                case 1:
                    $obj = $obj->where('hash', $keywords);
                    break;
                case 2:
                    $obj = $obj->where('name', 'like', "%{$keywords}%");
                    break;
            }
        }
        $listObj = $obj->orderByDesc('created_at')->paginate((int)$limit);

        return $this->buildSuccess([
            'list'  => $listObj->items(),
            'count' => $listObj->total()
        ]);
    }

    /**
     * 获取全部有效的接口组
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[GetMapping(path: 'getAll')]
    public function getAll(): array {
        $listInfo = AdminGroup::query()->where('status', 1)->get();

        return $this->buildSuccess([
            'list' => $listInfo
        ]);
    }

    /**
     * 接口组状态编辑
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[GetMapping(path: 'changeStatus')]
    public function changeStatus(): array {
        $id = $this->request->query('id');
        $status = $this->request->query('status');
        AdminGroup::query()->where('id', $id)->update(['status' => $status]);

        return $this->buildSuccess();
    }

    /**
     * 添加接口组
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[PostMapping(path: 'add')]
    public function add(): array {
        $infoObj = new AdminGroup();
        $infoObj->name = $this->request->post('name', '');
        $infoObj->description = $this->request->post('description', '');
        $infoObj->hash = $this->request->post('hash', '');
        $infoObj->image = $this->request->post('image', '');
        $infoObj->save();

        return $this->buildSuccess();
    }

    /**
     * 接口组编辑
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[PostMapping(path: 'edit')]
    public function edit(): array {
        $postData = $this->filterData((new AdminGroup())->getTable(), $this->request->post());
        AdminGroup::query()->where('id', $postData['id'])->update($postData);

        return $this->buildSuccess();
    }

    /**
     * 接口组删除
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[GetMapping(path: 'del')]
    public function del(): array {
        $hash = $this->request->query('hash');
        if (!$hash) {
            return $this->buildFailed(ErrorCode::EMPTY_PARAMS, '缺少必要参数');
        }
        if ($hash === 'default') {
            return $this->buildFailed(ErrorCode::INVALID, '系统预留关键数据，禁止删除！');
        }

        AdminList::query()->where('group_hash', $hash)->update(['group_hash' => 'default']);
        $hashRule = AdminApp::query()->where('app_api_show', 'like', "%$hash%")->get();
        if ($hashRule) {
            foreach ($hashRule as $rule) {
                $appApiShowArr = json_decode($rule->app_api_show, true);
                if (!empty($appApiShowArr[$hash])) {
                    if (isset($appApiShowArr['default'])) {
                        $appApiShowArr['default'] = array_merge($appApiShowArr['default'], $appApiShowArr[$hash]);
                    } else {
                        $appApiShowArr['default'] = $appApiShowArr[$hash];
                    }
                }
                unset($appApiShowArr[$hash]);
                $rule->app_api_show = json_encode($appApiShowArr);
                $rule->save();
            }
        }
        AdminGroup::query()->where('hash', $hash)->delete();

        return $this->buildSuccess();
    }
}
